#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<assert.h>
#include <ctype.h>
#define ERR_EXIT(m) \
    do { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while (0)


#define LEN 1024

int http_content_read(char* buf, size_t size, const char* path);
int print_content(const char* recvbuf, size_t n);

int main(int argc, char* argv[])
{
    if(argc < 2) {
        fprintf(stderr, "usage : ./httpclient ip_addr [port]\n");
        exit(EXIT_FAILURE);
    }

    char* ip_addr = argv[1];
    int port = 80;
    if(argc >= 3) {
        port = atol(argv[2]); 
    }

    int sock;
    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
        ERR_EXIT("socket error");
    }

    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = inet_addr(ip_addr);
    /* inet_aton("127.0.0.1", &servaddr.sin_addr); */

    if (connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        ERR_EXIT("connect error");
    }

    char buf_req[LEN];
    http_content_read(buf_req, LEN, "httpserver/req.txt");

    int n = write(sock, buf_req, strlen(buf_req));
    assert(n == strlen(buf_req));

    int ntotal = 0;

    while(1) {
        char recvbuf[1024] = {0};
        memset(recvbuf, 0, sizeof(recvbuf));
        int n = read(sock, recvbuf, sizeof(recvbuf));
        if(n < 0) {
            printf("\nread error.(%s).\n", strerror(errno));
            break;
        }
        else if(n == 0) {
            printf("\nn == 0.\n");
            sleep(1);
        }

        ntotal += n;
        //printf("total %10d, + %10d", ntotal, n); printf("\r");

        print_content(recvbuf, n);

        sleep(100);
    }

    close(sock);

    return 0;
}


int http_content_read(char* buf, size_t size, const char* path)
{
    int ret = 0;
    FILE* fp = fopen(path, "r");
    fread(buf, 1, size-1, fp);
    fclose(fp);
    return ret;
}


int print_content(const char* recvbuf, size_t n)
{
    int ret = 0;
    if(n == 0) return ret;

    int enable_print = 1;
    int ntmp = 0;
    char pstr[100];
    int i = 0;
    for(i=0; i<n; i++) {
        char ch = recvbuf[i];
        if(isprint(ch) || ch=='\r' || ch=='\n') {
            ntmp ++;
            if(ntmp > 10) {
                memcpy(pstr, &recvbuf[i-(ntmp-1)], ntmp);
                pstr[ntmp] = '\0';
                printf("%s", pstr);
                fflush(stdout);
                ntmp = 0;
            }
        }
        else {
            ntmp = 0;
        }

        //break;
        //printf("%c", ch);
                //fflush(stdout);
        
    }

    enable_print = 0;
    if(enable_print) {
        printf("%s\n", recvbuf);
    }

    return ret;
}
